package elitech.vietnam.weatherfashion.backgroundtask;

import java.util.ArrayList;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import elitech.vietnam.weatherfashion.MainActivity;
import elitech.vietnam.weatherfashion.R;
import elitech.vietnam.weatherfashion.config.GlobalValue;
import elitech.vietnam.weatherfashion.config.Utils;
import elitech.vietnam.weatherfashion.dto.MemberDTO;
import elitech.vietnam.weatherfashion.dto.NotificationDTO;
import elitech.vietnam.weatherfashion.service.PHPSoapServiceCaller;

public class NotificationBackGroundService extends Service {

	public static boolean isRunning = false;
	private final int NOTIFICATION_ID = 1234321;
	public static final String NOTIFICATION_MEMBERID_TAG = "NOTIFICATION_MEMBERID_TAG";
	public static final String NOTIFICATION_POSTID_TAG = "NOTIFICATION_POSTID_TAG";
	private final int TIME_RELOAD = 5000;
	// private Thread notificationThread;
	static public int NUMBER = 0;
	private boolean isLooped = false;

	private PHPSoapServiceCaller service = new PHPSoapServiceCaller();

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		isRunning = true;
		isLooped = true;
		new Thread(new Runnable() {
			@Override
			public void run() {

				Utils.Log("Vo duoc Notification service ");
				while (isLooped) {
					Utils.Log("Notification - looping");
					MemberDTO user = GlobalValue.getInstance(
							getApplicationContext()).readUserInfo();
					if (user != null) {
						try {
							ArrayList<NotificationDTO> listNotification = service
									.getNotification(user.getId());
							if (listNotification.size() > 0)
								createNewNotification(listNotification);

							// // updateNotification();
							// for (NotificationDTO notification :
							// listNotification) {
							// AppUtils.Log("Notification - i : "
							// + notification.getNotification());
							//
							//
							//
							// Thread.sleep(2000);
							// }

							Thread.sleep(TIME_RELOAD);
						} catch (Exception e) {
							Utils.Log("Loi notification service " + e);
						}
					} else {
						isLooped = false;
					}
				}
				Utils.Log("Out Notification looping ");
			}
		}).start();

		return super.onStartCommand(intent, flags, startId);
	}

	private String getNotificationString(NotificationDTO notification) {
		String commented = " commented ";
		String onYourPost = " on your post ";
		String notifi = notification.getNotification();
		try {

			if (getApplication() != null) {
				commented = getApplication().getString(
						R.string.string_word_comment);
				onYourPost = getApplication().getString(
						R.string.string_word_on_your_post);
			}

			String st[] = notification.getNotification().split("@@##@@##");
			notifi = st[0] + commented + st[1] + onYourPost + st[2];
		} catch (Exception e) {
		}
		return notifi;
	}

	private void createNewNotification(
			ArrayList<NotificationDTO> listNotification) {
		NotificationDTO notification = listNotification.get(listNotification
				.size() - 1);
		NUMBER += listNotification.size();

		String titleString = NUMBER
				+ getApplication().getString(R.string.string_words_new_message);

		Utils.Log("Notifications: " + listNotification.size());
		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
				this).setSmallIcon(R.drawable.ic_launcher24)
				.setContentTitle(titleString)
				.setContentText(getNotificationString(notification));

		// Creates an explicit intent for an Activity in your app
		// Intent resultIntent = new Intent(this, MainActivity.class);
		Intent resultIntent = new Intent(this, MainActivity.class);

		resultIntent.putExtra(NOTIFICATION_MEMBERID_TAG,
				notification.getMemberId());
		resultIntent
				.putExtra(NOTIFICATION_POSTID_TAG, notification.getPostId());
		resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
		// Adds the back stack for the Intent (but not the Intent itself)
		stackBuilder.addParentStack(MainActivity.class);
		// Adds the Intent that starts the Activity to the top of the stack
		stackBuilder.addNextIntent(resultIntent);

		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
				PendingIntent.FLAG_UPDATE_CURRENT);
		mBuilder.setContentIntent(resultPendingIntent);
		Uri alarmSound = RingtoneManager
				.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
		mBuilder.setSound(alarmSound);

		mBuilder.setAutoCancel(true);
		mBuilder.setNumber((NUMBER));

		// ///////////////////////////////////
		NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

		// Sets a title for the Inbox style big view
		inboxStyle.setBigContentTitle(titleString);

		// Moves events into the big view
		for (int i = 0; i < listNotification.size(); i++) {

			inboxStyle.addLine((i + 1) + " - "
					+ getNotificationString(listNotification.get(i)));
		}
		// Moves the big view style object into the notification object.
		mBuilder.setStyle(inboxStyle);
		// ////////////////////////

		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		// mId allows you to update the notification later on.
		mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

	}

	@Override
	public IBinder onBind(Intent arg0) {
		isRunning = true;
		isLooped = true;
		return null;
	}

	@Override
	public boolean onUnbind(Intent intent) {
		Utils.Log("onUnbind Notification service ");
		return super.onUnbind(intent);

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		isRunning = false;
		isLooped = false;
		Utils.Log("onDestroy Notification service ");
	}

}
